let express = require('express');
let app = express();
let router = express.Router();
let wechat = require('wechat');
let wxapi = require('wechat-api');
let path = require('path');
let fs = require('fs');
let http = require('http');
let bodyParser = require('body-parser');
let ueditor = require("ueditor");
let status = require('../common/statusConfig');
let defaults = require('../common/default.json');
let multerUtil = require('../common/multer-util');
let mongoose = require('mongoose');
let jwt = require('jwt-simple');
let moment = require('moment');

let User = require("./../models/user");
let admin = require("./../models/admin");
let Tag = require("./../models/Tag");
let replyContent = require("./../models/replyContent");
let materigl = require("./../models/material");

//链接mongo数据库
mongoose.connect("mongodb://127.0.0.1:27017/testMongoDB");
mongoose.connection.on("connected", function () {
    console.log("mongodb connect success")
});
mongoose.connection.on("error", function () {
    console.log("1")
});
let appid = defaults.wxconfig.appid;
let appsecret = defaults.wxconfig.appsecret;
let api = new wxapi(appid, appsecret);

router.use(bodyParser.urlencoded({
    extended: true
}))
router.use(bodyParser.json());
//  网址配置
let Website = 'http://1798xt1229.iask.in/'
app.set('jwtTokenSecret', 'guanshanhu'); // token加盐
router.use(function (req, res, next) {  // 接口token验证
    let url = '/weChat' + req._parsedUrl.pathname
    if (url !== '/weChat/login' && url !== '/weChat' && url !== '/weChat/wximg') {
        // let token = (req.body && req.body.access_token) || (req.query && req.query.access_token) || req.headers['x-access-token'];
        let token = req.headers['x-access-token'];
        if (token) {
            try {
                var decoded = jwt.decode(token, app.get('jwtTokenSecret'));
                if (decoded.exp <= Date.now()) {
                    return res.json({
                        code: 401,
                        msg: '登录过期'
                    });
                }
                next();
                // handle token here
            } catch (err) {
                return res.json({
                    code: 401,
                    msg: '未登录'
                });
            }
        } else {
            return res.json({
                code: 401,
                msg: '未登录'
            });
        }
    } else {
        next();
    }
})
// 微信后台登录
router.post('/login', function (req, res, next) {
    let userName = req.body.userName
    let password = req.body.password
    admin.findOne({userName: userName}, function (err, user) {
        if (err) {
            // user not found
            return res.json({
                code: 401
            });
        }
        if (!user || !(user.password === password)) {
            // incorrect password
            return res.json({
                code: -1,
                msg: '帐号或密码错误',
                user: {}
            });
        }
        // User has authenticated OK
        let expires = moment().add('days', 7).valueOf();
        let token = jwt.encode({
            iss: user.userName,
            exp: expires
        }, app.get('jwtTokenSecret'));
        res.json({
            code: 1,
            user: {
                token: token,
                expires: expires,
                userName: user.userName,
                nickname: user.nickname
            }
        });
    });
})
// admin.create({"userName": 'admin',
//     "password": 123456,
//     "nickname": 'admin',
//     "time": +new Date()})

// /ueditor 入口地址配置 https://github.com/netpi/ueditor/blob/master/example/public/ueditor/ueditor.config.js
// 官方例子是这样的 serverUrl: URL + "php/controller.php"
// 我们要把它改成 serverUrl: URL + 'ue'
router.use("/ueditor/ue", ueditor(path.join(__dirname, '../public'), function (req, res, next) {
    // ueditor 客户发起上传图片请求
    if (req.query.action === 'uploadimage') {

        // 这里你可以获得上传图片的信息
        var foo = req.ueditor;
        // 下面填写你要把图片保存到的路径 （ 以 path.join(__dirname, 'public') 作为根路径）
        var img_url = '/upload/img';

        res.ue_up(img_url); //你只要输入要保存的地址 。保存操作交给ueditor来做
    }
    //  客户端发起图片列表请求
    else if (req.query.action === 'listimage') {
        var dir_url = '/upload/img'; // 要展示给客户端的文件夹路径
        res.ue_list(dir_url) // 客户端会列出 dir_url 目录下的所有图片
    }
    // 客户端发起其它请求
    else {
        res.setHeader('Content-Type', 'application/json');
        // 这里填写 ueditor.config.json 这个文件的路径
        res.redirect('http://localhost:8080/static/ueditor/config.json')
    }
}));
router.all('/', wechat(defaults.wxconfig)
    .text(function (message, req, res, next) {
        let content = message.Content || null;
        let textContent = '';
        let openid = message.FromUserName;
        //最大值
        Array.prototype.max = function () {
            let max = this[0],
                index = [0];
            let len = this.length;
            for (let i = 1; i < len; i++) {
                if (this[i] === max) {
                    index.push(i);
                }
                if (this[i] > max) {
                    max = this[i];
                    index = [i];
                }
            }
            return index;
        }
        replyContent.find({textKey: {$regex: new RegExp(content, 'i')}}, {}, function (err, docs) {
            if (err) {
                console.log(err)
                res.reply('')
            }

            function newsSend(data) {
                if (data.newsData.media_id === null) {
                    textContent = data.newsData.news
                } else {
                    api.sendMpNews(openid, data.newsData.media_id, function (err, result) {
                        if (err) {
                            console.info(err)
                            return
                        }
                        res.reply();
                        return
                    });
                }
            }

            if (docs.length > 1) {
                let arr = [];
                docs.forEach(function (item, index) {
                    arr.push(item.weight)
                })
                let maxIndex = arr.max()
                if (maxIndex.length > 1) {
                    // 多个相同权重的 随机获取一个
                    var random = Math.ceil(Math.random() * maxIndex.length) - 1;
                    if (docs[maxIndex[random]].type === 'text') {
                        textContent = docs[maxIndex[random]].textVal
                    } else {
                        newsSend(docs[maxIndex[random]])
                    }
                } else {
                    if (docs[0].type === 'text') {
                        textContent = docs[maxIndex[0]].textVal
                    } else {
                        newsSend(docs[0])
                    }
                }
            } else if (docs.length === 1) {
                if (docs[0].type === 'text') {
                    textContent = docs[0].textVal;
                } else {
                    newsSend(docs[0])
                }
            }
            res.reply(textContent);
        })
    }).image(function (message, req, res, next) {
        res.reply([
            {
                "title": "Happy Day",
                "description": "Is Really A Happy Day",
                "url": "http://1798xt1229.iask.in/upload/img/966865927113150464.jpg",
                "picurl": "http://1798xt1229.iask.in/upload/img/966865927113150464.jpg",
            }
        ]);
    }).voice(function (message, req, res, next) {
        res.reply('语音已收到');
    }).video(function (message, req, res, next) {
        res.reply('视频已收到');
    }).location(function (message, req, res, next) {
        res.reply('地理位置已收到');
    }).link(function (message, req, res, next) {
        res.reply('链接已收到');
    }).event(function (message, req, res, next) {
        switch (message.Event) {
            case 'subscribe':
                res.reply('欢迎关注一介布衣公众号');
                break;
            case 'unsubscribe':
                res.reply('亲,请不要离开我!!');
                break;
            case 'CLICK':
                replyContent.find({menuKey: message.EventKey}, function (err, docs) {
                    if (err) {
                        console.info(err)
                        return
                    }
                    if (docs[0].type === 'text') {
                        res.reply(docs[0].textVal);
                    } else {
                        if (docs[0].newsData.media_id === null) {
                            res.reply(docs[0].newsData.news);
                        } else {
                            api.sendMpNews(message.FromUserName, docs[0].newsData.media_id, function (err, result) {
                                if (err) {
                                    console.info(err)
                                    return
                                }
                                res.reply();
                                return
                            });
                        }
                    }
                });
                // console.log(message)
                break;
            default :
                res.send('');
        }
    }).device_text(function (message, req, res, next) {
        res.reply('设备消息已收到');
    }).device_event(function (message, req, res, next) {
        res.reply('设备事件已收到');
    }).middlewarify()
);
// 微信图片获取
router.get('/wximg', function (req, res, next) {
    let url = req.query.url;

    function GetRequest(url, strName) {
        let intPos = url.indexOf("?");  // 参数开始位置
        let strRight = url.substr(intPos + 1);
        let arrTmp = strRight.split("&"); //参数分割符
        for (let i = 0; i < arrTmp.length; i++) {
            let arrTemp = arrTmp[i].split("=");
            if (arrTemp[0].toUpperCase() === strName.toUpperCase()) return arrTemp[1];
        }
    }

    http.get(url, function (data) {
        let imgData = "";
        data.setEncoding("base64"); //一定要设置response的编码为binary否则会下载下来的图片打不开
        data.on("data", function (chunk) {
            imgData += chunk;
        });
        data.on("end", function () {
            res.write(imgData, 'base64');
            res.send()
        });
    });
})
// 微信图片获取
// router.get('/img', function (req, res, next) {
//     let url = req.query.url;
//
//     function GetRequest(url, strName) {
//         let intPos = url.indexOf("?");  // 参数开始位置
//         let strRight = url.substr(intPos + 1);
//         let arrTmp = strRight.split("&"); //参数分割符
//         for (let i = 0; i < arrTmp.length; i++) {
//             let arrTemp = arrTmp[i].split("=");
//             if (arrTemp[0].toUpperCase() === strName.toUpperCase()) return arrTemp[1];
//         }
//     }
//
//     http.get(url, function (data) {
//         let imgData = "";
//         let fileUrl = "/upload/wxImg/" + (+new Date()) + '.' + GetRequest(url, 'wx_fmt');
//         data.setEncoding("binary"); //一定要设置response的编码为binary否则会下载下来的图片打不开
//         data.on("data", function (chunk) {
//             imgData += chunk;
//         });
//         data.on("end", function () {
//             fs.writeFile("./public" + fileUrl, imgData, "binary", function (err, data) {
//                 if (err) {
//                     console.log("down fail");
//                 }
//                 res.json({data: Website + fileUrl});
//             });
//         });
//     });
// })
/* 上传图片 */
router.post('/uploadImg', multerUtil.single('file'), function (req, res, next) {
    res.json({
        result: Website + req.file.path.slice(7, req.file.path.length),
        code: status.success,
        msg: '上传成功！'
    });
});

/* 添加图文素材 */
router.post('/addNews', function (req, res, next) {
    let news = req.body.newsData
    let newsType = req.body.newsType
    let isReply = req.body.isReply || 'yes'
    let id = news._id ? mongoose.Types.ObjectId(news._id) : mongoose.Types.ObjectId(null);

    function neweMongdb(media_id) {
        return new Promise(function (resolve, reject) {
            materigl.update({"content.media_id": media_id}, {
                "type": 'news',  //素材的类型，图片（image）、视频（video）、语音 （voice）、图文（news）
                "content": {
                    news: news.news,
                    media_id: newsType ? media_id : null
                }
            }, {upsert: true}, function (err, docs) {
                if (err) {
                    console.info(err)
                    reject()
                    return
                }
                resolve({docs: docs, media_id: media_id})
            })
        })
    }

    function replyContentUpdate(data) {
        let mo = {
            'title': news.title,
            'menuKey': news.menuKey,
            'textKey': news.textKey,
            'type': news.type,
            'newsData': {
                id: data.docs.upserted[0]._id,
                media_id: newsType ? data.media_id : null
            },
            'weight': Number(news.weight)
        }
        replyContent.update({_id: id}, mo, {upsert: true}, function (err, docs) {
            if (err) {
                res.json({
                    code: status.fail,
                    msg: '上传本地服务器失败！'
                });
                return
            }
            res.json({
                code: status.success,
                msg: '上传成功！'
            });
        })
    }

    function menuKeyIf() {
        if (newsType) {
            api.uploadNewsMaterial({articles: news.news}, function (err, result) {
                if (err) {
                    console.info(result)
                    res.json({
                        result: result,
                        code: status.fail,
                        msg: '上传微信服务器失败！'
                    });
                    return
                }
                neweMongdb(result.media_id).then(function (data) {
                    if(isReply === 'yes'){
                        replyContentUpdate(data)
                    }else {
                        res.json({
                            code: status.success,
                            msg: '上传成功！'
                        });
                    }
                }, function (error) {
                    res.json({
                        code: status.fail,
                        msg: '上传本地服务器失败！'
                    });
                })
            });
        } else {
            neweMongdb().then(function (data) {
                replyContentUpdate(data)
            }, function (error) {
                res.json({
                    code: status.fail,
                    msg: '上传本地服务器失败！'
                });
            })
        }
    }

    if (!news.menuKey) {
        menuKeyIf()
    } else {
        replyContent.find({menuKey: news.menuKey}, {menuKey: 1}, function (err, docs) {
            if (err) {
                res.json({
                    code: status.fail,
                    msg: '获取文字回复列表失败'
                })
                return
            }
            if (docs.length > 0) {
                res.json({
                    code: status.fail,
                    msg: '菜单key值重复'
                });
                return
            }
            menuKeyIf()
        });
    }
});
// 从微信服务器拉取已有的素材
router.post('/WXgetMaterial', function (req, res, next) {
    let MaterialType = req.body.type
    getMaterials(MaterialType, 0, 20)
    console.info(MaterialType)

    function getMaterials(type, offset, count) {
        api.getMaterials(type, offset, count, function (err, result) {
                if (err) {
                    res.json({
                        result: result,
                        code: status.fail,
                        msg: '拉取素材失败！'
                    });
                    return
                }

                if (result.item.length <= 0) {
                    res.json({
                        code: status.success,
                        msg: '拉取素材成功'
                    });
                    return
                }
                if (MaterialType === 'news') {
                    news(result, type)
                } else if (MaterialType === 'image') {
                    image(result, type)
                }
            }
        );
    }

    function news(result, type) {
        result.item.forEach(function (item, index) {
            materigl.update({
                type: type,
                'content.media_id': item.media_id
            }, {'content.news': item.content.news_item}, {
                multi: true,
                upsert: true
            }, function (err, docs) {
                if (err) {
                    console.log(err)
                    res.json({
                        code: status.fail,
                        msg: '拉取素材失败'
                    });
                    return
                }
                if (index === result.item.length - 1) {
                    if (result.total_count !== result.item_count) {
                        getMaterials(MaterialType, 0, 20)
                    } else {
                        res.json({
                            code: status.success,
                            msg: '拉取素材成功'
                        });
                    }
                }
            })
        })
    }

    function image(result, type) {
        result.item.forEach(function (item, index) {
            materigl.update({
                type: type,
                'content.media_id': item.media_id
            }, {'content.url': item.url}, {
                multi: true,
                upsert: true
            }, function (err, docs) {
                if (err) {
                    console.log(err)
                    res.json({
                        code: status.fail,
                        msg: '拉取素材失败'
                    });
                    return
                }
                if (index === result.item.length - 1) {
                    if (result.total_count !== result.item_count) {
                        getMaterials(MaterialType, 0, 20)
                    } else {
                        res.json({
                            code: status.success,
                            msg: '拉取素材成功'
                        });
                    }
                }
            })
        })
    }
})
// 获取素材列表 
router.post('/getMaterial', function (req, res, next) {
    let id = req.body.id
    if (!id) {
        let currentPage = req.body.currentPage || 1
        let type = req.body.type
        materigl.find({type: type})
            .skip((currentPage - 1) * 20)
            .limit(20)
            .sort({'_id': -1})
            .exec(function (err, docs) {
                if (err) {
                    res.json({
                        code: status.fail,
                        msg: '获取素材列表失败'
                    });
                    return
                }
                if (currentPage === 1) {
                    materigl.count({type: type}, function (err, count) {
                        if (err) {
                            res.json({
                                code: status.fail,
                                msg: '获取素材列表失败'
                            });
                            return
                        }
                        console.info(count)
                        res.json({
                            data: {material: docs, TotalNumber: count, currentPage: currentPage},
                            code: status.success,
                            msg: '获取素材列表成功'
                        });
                    })
                } else {
                    res.json({
                        data: {material: docs, currentPage: currentPage},
                        code: status.success,
                        msg: '获取素材列表成功'
                    });
                }
            })
    } else {
        materigl.find({_id: id}, function (err, docs) {
            if (err) {
                res.json({
                    code: status.fail,
                    msg: '获取素材失败'
                });
                return
            }
            res.json({
                data: {content: docs[0].content},
                code: status.success,
                msg: '获取素材成功'
            });
        })
    }

})
// 素材群发
router.post('/MassMaterial', function (req, res, next) {
    let type = req.body.type
    let mediaId = req.body.mediaId
    let receivers = req.body.receivers

    function callback(err, result) {
        if (err) {
            res.json({
                result: result,
                code: status.fail,
                msg: '群发失败！'
            });
            return
        }
        res.json({
            code: status.success,
            msg: '群发成功！'
        });
    }

    if (type === 'news') {
        api.massSendNews(mediaId, receivers, callback);
    } else if (type === 'image') {
        api.massSendImage(mediaId, receivers, callback);
    } else if (type === 'text') {
        //mediaId此处的为文本内容
        api.massSendText(mediaId, receivers, callback);
    }
})
/* 上传永久素材 */
router.post('/uploadPerpetualMaterial', multerUtil.single('file'), function (req, res, next) {
    api.uploadMaterial(req.file.path, req.query.type, function (err, result) {
        if (err) {
            res.json({
                result: result,
                code: status.fail,
                msg: '上传失败！'
            });
            return
        }
        let deleteFolderRecursive = function (url) {
            if (fs.existsSync(url)) {
                fs.unlinkSync(url);
            } else {
                console.log("给定的路径不存在，请给出正确的路径");
            }
        };
        deleteFolderRecursive(req.file.path);
        res.json({
            result: result,
            code: status.success,
            msg: '上传成功！'
        });
    });
});
// 图文预览
router.post('/previewNews', function (req, res, next) {
    let openid = req.body.openid
    let mediaId = req.body.mediaId
    let articles = req.body.news
    let type = req.body.type

    function callback(err, result) {
        if (err) {
            res.json({
                result: result,
                code: status.fail,
                msg: '预览失败！'
            });
            return
        }
        res.json({
            code: status.success,
            msg: '预览成功！'
        });
    }

    if (type === 'news') {
        if (mediaId === null) {
            api.sendNews(openid, articles, callback);
        } else {
            api.previewNews(openid, mediaId, callback);
        }
    } else if (type === 'image') {
        api.previewImage(openid, mediaId, callback);
    }

})
// 删除永久素材
router.post('/delMaterial', function (req, res, next) {
    let media_id = req.body.media_id
    let id = req.body.id
    api.removeMaterial(media_id, function (err, result) {
        if (err) {
            res.json({
                result: result,
                code: status.fail,
                msg: '删除失败！'
            });
            return
        }
        materigl.remove({_id: id}, function (err, docs) {
            if (err) {
                res.json({
                    code: status.fail,
                    msg: '本地数据库删除失败！'
                });
                return
            }
            res.json({
                result: result,
                code: status.success,
                msg: '删除成功！'
            });
        })
    });
})
/* 删除回复 */
router.post('/deleteReply', function (req, res, next) {
    let _id = req.body._id
    replyContent.remove({_id: _id}, function (err, docs) {
        if (err) {
            res.json({
                code: status.fail,
                msg: '删除成功！'
            });
            return
        }
        res.json({
            textDataList: docs,
            code: status.success,
            msg: '删除失败！'
        });
    })
})
/* 回复列表获取 */
router.get('/replyList', function (req, res, next) {
    // 没传type 为 菜单设置时获取key值时用的  text 为文本回复 news为图文回复
    let type = req.query.type
    let options = {};
    let condition = {};
    if (type) {
        options = (type === 'text' ? {menuid: 0} : {textVal: 0})
        condition = {type: type}
    } else {
        options = {title: 1, menuKey: 1, type: 1}
        condition = {menuKey: /^\S/}
    }
    replyContent.find(condition, options, function (err, docs) {
        if (err) {
            res.json({
                code: status.fail,
                msg: '获取回复列表失败'
            })
            return
        }
        res.json({
            textDataList: docs,
            code: status.success,
            msg: '获取回复列表成功！'
        });
    })
})
/* 文字回复设置 */
router.post('/replyContent', function (req, res, next) {
    let textData = req.body.textData
    //使用_id 为条件需要用 mongoose.Types.ObjectId() 处理
    let id = textData._id ? mongoose.Types.ObjectId(textData._id) : mongoose.Types.ObjectId(null);
    let mo = {
        'title': textData.title,
        'menuKey': textData.menuKey,
        'textKey': textData.textKey,
        'type': textData.type,
        'textVal': textData.textVal,
        'weight': Number(textData.weight)
    }
    replyContent.find({menuKey: textData.menuKey}, {menuKey: 1}, function (err, docs) {
        if (err) {
            res.json({
                code: status.fail,
                msg: '获取文字回复列表失败'
            })
            return
        }
        if (docs.length > 0) {
            res.json({
                code: status.fail,
                msg: '菜单key值重复'
            });
            return
        }
        replyContent.update({_id: id}, mo, {upsert: true}, function (err, docs) {
            if (err) {
                res.json({
                    code: status.fail,
                    msg: '添加文字回复失败！'
                });
                return
            }
            res.json({
                code: status.success,
                msg: '添加文字回复成功！'
            });
        })
    });
})
/* 菜单删除 */
router.post('/removeMenu', function (req, res, next) {
    let menuType = req.body.menuType
    let menuid = req.body.menuid
    // 1 为自定义菜单 0为个性化菜单
    if (menuType === 1) {
        api.removeMenu(function (err, result) {
            if (err) {
                res.json({
                    code: status.fail,
                    msg: '删除自定义菜单失败'
                });
                return
            }
            res.json({
                code: status.success,
                msg: '删除自定义菜单成功'
            });
        });
    } else {
        api.removeCustomMenu(menuid, function (err, result) {
            if (err) {
                res.json({
                    code: status.fail,
                    msg: '删除个性化菜单失败'
                });
                return
            }
            res.json({
                code: status.success,
                msg: '删除个性化菜单成功'
            });
        });
    }
});
/* 菜单查询 */
router.get('/getMenu', function (req, res, next) {
    api.getMenu(function (err, result) {
        if (err) {
            res.json({
                code: status.fail,
                msg: '创建自定义菜单失败'
            });
            return
        }
        res.json({
            menuData: result,
            code: status.success,
            msg: '创建自定义菜单成功'
        });
    });
});
/* 个性化菜单 */
router.post('/IndividualizationMenu', function (req, res, next) {
    let menuData = req.body.data;
    api.createCustomMenu(menuData, function (err, result) {
        if (err) {
            res.json({
                code: status.fail,
                msg: '创建自定义菜单失败'
            });
            return
        }
        res.json({
            code: status.success,
            msg: '创建自定义菜单成功'
        });
    });
});
/* 自定义菜单. */
router.post('/createMenu', function (req, res, next) {
    let menuData = req.body.data;
    api.createMenu(menuData, function (err, result) {
        if (err) {
            res.json({
                code: status.fail,
                msg: '创建自定义菜单失败'
            });
            return
        }
        res.json({
            code: status.success,
            msg: '创建自定义菜单成功'
        });
    });
});
/* 从微信服务器拉取用户列表 */
router.post('/WXuserList', function (req, res, next) {
    let synchro = req.body.synchro
    let openids = req.body.openids
    // 全部同步 allsynchro 和 部分同步 synchro
    if (synchro === 'synchro') {
        api.batchGetUsers(openids, function (err, result) {
            if (err) {
                res.json({
                    result: result,
                    code: status.fail,
                    msg: '获取用户信息失败'
                });
                return
            }
            const user_info_list = result.user_info_list;
            let userUpdateArr = [];
            user_info_list.forEach(function (item, index) {
                userUpdateArr.push({
                    updateOne: {
                        filter: {openid: item.openid},
                        update: item
                    }
                })
            })
            User.bulkWrite(userUpdateArr, function (err, docs) {
                if (err) {
                    console.log(err)
                    res.json({
                        code: status.fail,
                        msg: '存储用户信息失败'
                    });
                    return
                }
                res.json({
                    code: status.success,
                    msg: '拉取粉丝列表已完成，请刷新页面'
                });
            })
        })
    } else {
        userList();
    }

// 拉取用户信息
    function ObtainUser(openidList) {
        return new Promise((resolve, reject) => {
            api.batchGetUsers(openidList, function (err, result) {
                if (err) {
                    res.json({
                        code: status.fail,
                        msg: '获取用户信息失败'
                    });
                    return
                }
                resolve({data: result.user_info_list})
            })
        })
    }

    // 存储用户信息
    function updataUser(arr, next_openid, openidList) {
        arr.forEach(function (item, index) {
            Tag.find({id: item.tagid_list}, function (err, docs) {
                if (err) {
                    console.log(err)
                    res.json({
                        code: status.fail,
                        msg: '存储用户信息失败'
                    });
                    return
                }
                item.tagName_list = []
                for (let i = 0; i < docs.length; i++) {
                    item.tagName_list.push(docs[i].name)
                }
                User.update({"openid": item.openid}, item, {
                    multi: true,
                    upsert: true
                }, function (err, docs) {
                    if (err) {
                        console.log(err)
                        res.json({
                            code: status.fail,
                            msg: '存储用户信息失败'
                        });
                        return
                    }
                    if (index === openidList.length - 1) {
                        if (next_openid !== openidList[openidList.length - 1]) {
                            userList(next_openid);
                        } else {
                            res.json({
                                code: status.success,
                                msg: '拉取粉丝列表已完成，请刷新页面'
                            });
                        }
                    }
                })
            })
        })
    }

// 拉取用户列表
    function userList(nextOpenid) {
        nextOpenid = !!nextOpenid ? nextOpenid : "";
        api.getFollowers(nextOpenid, function (err, result) {
            if (err) {
                res.json({
                    code: status.fail,
                    msg: '获取用户信息失败'
                });
                return
            }
            let next_openid = result.next_openid;
            let openidList = result.data.openid;
            let userListArr = []
            if (openidList.length > 100) {
                let dyadicOpenidList = [];
                let openidArrLength = Math.ceil(openidList.length / 100)
                for (let i = 0; openidArrLength > i; i++) {
                    dyadicOpenidList.push(openidList.slice(i * 100, i * 100 + 100))
                }
                new Promise((resolve, reject) => {
                    let count = 0
                    dyadicOpenidList.forEach(function (item, index) {
                        ObtainUser(item).then(function (data) {
                            userListArr = userListArr.concat(data.data)
                            count++
                            if (count === openidArrLength) {
                                resolve()
                            }
                        })
                    })
                }).then(() => {
                    updataUser(userListArr, next_openid, openidList)
                })

            } else {
                ObtainUser(openidList).then(function (data) {
                    userListArr = userListArr.concat(data.data)
                    updataUser(userListArr, next_openid, openidList)
                })
            }
        })
    }
});
// 给用户设置备注
router.post('/setRemarks', function (req, res, next) {
    let remarks = req.body.remarks,
        openid = req.body.openid;
    api.updateRemark(openid, remarks, function (err, result) {
        if (err) {
            res.json({
                result: result,
                code: status.fail,
                msg: '设置备注失败'
            })
            return
        }
        User.update({openid: openid}, {remark: remarks}, function (err, docs) {
            if (err) {
                res.json({
                    code: status.fail,
                    msg: '设置备注失败'
                })
                return
            }
            res.json({
                code: status.success,
                msg: '设置备注成功'
            });
        })
    });
})
// 给用户打标签
router.post('/bindTag', function (req, res, next) {
    let openids = req.body.openids,
        tagId = req.body.tagId,
        tagName = req.body.tagName
    api.membersBatchtagging(tagId, openids, function (err, result) {
        if (err) {
            res.json({
                result: result,
                code: status.fail,
                msg: '打标签失败'
            });
            return
        }
        User.update({openid: openids}, {'$addToSet': {tagid_list: tagId, tagName_list: tagName}}, {
            multi: true,// 允许多条
            upsert: true// 没有就创建 有更新
        }, function (err, docs) {
            if (err) {
                console.log(err)
                res.json({
                    code: status.fail,
                    msg: '本地存储失败，请同步该次打标签的用户'
                });
                return
            }
            Tag.update({id: tagId}, {'$inc': {count: openids.length}}, function (err, docs) {
                if (err) {
                    console.log(err)
                    res.json({
                        code: status.fail,
                        msg: '标签组添加失败，请同步标签组以获取最新信息'
                    });
                    return
                }
                res.json({
                    code: status.success,
                    msg: '打标签成功'
                });
            })
        })
    });
})
// 给用户取消标签
router.post('/cancelTag', function (req, res, next) {
    let tagId = req.body.tagId,
        tagName = req.body.tagName,
        openList = req.body.openids;
    api.membersBatchuntagging(tagId, openList, function (err, result) {
        if (err) {
            res.json({
                result: result,
                code: status.fail,
                msg: '取消标签失败'
            });
            return
        }
        User.update({openid: openList}, {'$pull': {tagid_list: tagId, tagName_list: tagName}}, {
            multi: true,// 允许多条
            upsert: true// 没有就创建 有更新
        }, function (err, docs) {
            if (err) {
                console.log(err)
                res.json({
                    code: status.fail,
                    msg: '本地存储失败，请同步该次取消标签的用户'
                });
                return
            }
            Tag.update({id: tagId}, {'$inc': {count: -openList.length}}, function (err, docs) {
                if (err) {
                    console.log(err)
                    res.json({
                        code: status.fail,
                        msg: '标签组修改失败，请同步标签组以获取最新信息'
                    });
                    return
                }
                res.json({
                    code: status.success,
                    msg: '取消标签成功'
                });
            })
        })
    });
})
// 从数据库中获取用户信息
router.post('/userList', function (req, res, next) {
    let currentPage = req.body.currentPage || 1;
    let form = req.body.form; // 筛选条件
    console.info(form)
    // let id = req.body.id
    // let subscribe = (form.folllow !== '全部'?subscribe: (form.folllow):'')
    let condition = {};
    if (form.openid === '') {
        console.info(form.follow !== '全部')
        if (form.follow !== '全部') {
            condition.subscribe = form.follow === '未关注' ? 0 : 1
        }
        if (form.TagId !== '') {
            condition.tagid_list = form.TagId
        }
        if (form.dateMin !== '' || form.dateMax !== '') {
            if (form.dateMin === '') {
                condition.subscribe_time = {'$lte': form.dateMax / 1000}
            } else if (form.dateMax === '') {
                condition.subscribe_time = {'$gte': form.dateMin / 1000}
            } else {
                condition.subscribe_time = {'$gte': form.dateMin / 1000, '$lte': form.dateMax / 1000}
            }
        }
    } else {
        condition.openid = form.openid
    }
    User.find(condition)
        .skip((currentPage - 1) * 20)
        .limit(20)
        .sort({'_id': -1})
        .exec(function (err, docs) {
            if (err) {
                console.info(err)
                res.json({
                    code: status.fail,
                    msg: '获取用户信息失败'
                });
                return
            }
            if (currentPage === 1) {
                User.count({}, function (err, count) {
                    if (err) {
                        res.json({
                            code: status.fail,
                            msg: '获取用户信息失败'
                        });
                        return
                    }
                    res.json({
                        data: {userData: docs, TotalNumber: count, currentPage: currentPage},
                        code: status.success,
                        msg: '获取用户信息成功'
                    });
                })
            } else {
                res.json({
                    data: {userData: docs, currentPage: currentPage},
                    code: status.success,
                    msg: '获取用户信息成功'
                });
            }
        })
})
// 从微信获取标签组
router.post('/WXtagList', function (req, res, next) {
    api.getTags(function (err, result) {
        if (err) {
            res.json({
                result: result,
                code: status.fail,
                msg: '获取标签失败'
            });
            return
        }
        let tagList = result.tags;
        tagList.forEach(function (item, index) {
            Tag.update({id: item.id}, item, {
                multi: true,// 允许多条
                upsert: true// 没有就创建 有更新
            }, function (err, docs) {
                if (err) {
                    console.info(err)
                    res.json({
                        code: status.fail,
                        msg: '获取标签失败'
                    });
                    return
                }
                if (index === tagList.length - 1) {
                    res.json({
                        code: status.success,
                        msg: '获取标签成功'
                    });
                }
            })
        })
    });
})
// 获取标签组 本地服务器
router.post('/tagList', function (req, res, next) {
    Tag.find({}, {__v: 0}, function (err, docs) {
        if (err) {
            res.json({
                code: status.fail,
                msg: '获取标签信息失败'
            });
            return
        }
        res.json({
            data: docs,
            code: status.success,
            msg: '获取标签信息成功'
        });
    })
})
// 修改、添加标签名
router.post('/modifyTag', function (req, res, next) {
    let id = req.body.id,
        oldName = req.body.oldName,
        name = req.body.name;
    if (id) {
        api.editTag(id, name, function (err, result) {
            if (err) {
                res.json({
                    result: result,
                    code: status.fail,
                    msg: '修改标签失败'
                });
                return
            }
            Tag.update({id: id}, {name: name}, function (err, docs) {
                if (err) {
                    res.json({
                        code: status.fail,
                        msg: '数据库修改失败'
                    });
                    return
                }
                // 修改数组中的某个值
                User.update({tagName_list: oldName}, {$set: {"tagName_list.$": name}}, {
                    multi: true,// 允许多条
                    upsert: true// 没有就创建 有更新
                }, function (err, docs) {
                    if (err) {
                        res.json({
                            code: status.fail,
                            msg: '数据库修改失败'
                        });
                        return
                    }
                    res.json({
                        code: status.success,
                        msg: '修改标签成功'
                    });
                })
            })
        });
    } else {
        api.createTag(name, function (err, result) {
            if (err) {
                res.json({
                    result: result,
                    code: status.fail,
                    msg: '添加标签失败'
                });
                return
            }
            Tag.create(result.tag, function (err, docs) {
                if (err) {
                    res.json({
                        result: result,
                        code: status.fail,
                        msg: '存入数据库失败'
                    });
                    return
                }
                res.json({
                    result: result,
                    code: status.success,
                    msg: '添加标签成功'
                });
            })
        });
    }
})
// 删除标签
router.post('/delTag', function (req, res, next) {
    let id = req.body.id;
    let name = req.body.name;
    api.deleteTag(id, function (err, result) {
        if (err) {
            res.json({
                result: result,
                code: status.fail,
                msg: '删除标签失败'
            });
            return
        }
        Tag.remove({id: id}, function (err, docs) {
            if (err) {
                res.json({
                    code: status.fail,
                    msg: '删除标签失败'
                });
                return
            }
            User.update({tagid_list: id}, {'$pull': {tagid_list: id, tagName_list: name}}, {
                multi: true,// 允许多条
                upsert: true// 没有就创建 有更新
            }, function () {
                if (err) {
                    res.json({
                        code: status.fail,
                        msg: '用户标签信息更新失败，请重新同步用户信息'
                    });
                    return
                }
                res.json({
                    code: status.success,
                    msg: '删除标签成功'
                });
            })
        })
    });
})


module.exports = router;
